package com.example.demo.services.impl;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.dao.MessageMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Message;
import com.example.demo.model.User;
import com.example.demo.services.IMessageService;
import com.example.demo.services.IUserService;
import com.example.demo.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private IUserService userService;


    @Override
    public void create(Message message) {
        //非空效验
        if(message==null || message.getReceiveUserId()==null
                || message.getPostUserId()==null || StringUtil.isEmpty(message.getContent()))
        {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //接受者是否存在
        User user=userService.selectById(message.getReceiveUserId());
        if(user==null || user.getDeleteState()==1)
        {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"userId="+user.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //设置默认值
        message.setDeleteState((byte) 0);
        message.setState((byte) 0);
        Date date=new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);

        // 调用DAO
        int row = messageMapper.insertSelective(message);
        if (row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    @Override
    public Integer selectUnreadCount(Long receiveUserId) {
        // 非空校验
        if (receiveUserId == null || receiveUserId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 直接调用DAO
        Integer count = messageMapper.selectUnreadCount(receiveUserId);
        // 正常的查询是不可能出现null，如果为null则抛出异常
        if (count == null) {

            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        // 返回结果
        return count;
    }

    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        // 非空校验
        if (receiveUserId == null || receiveUserId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用DAO
        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);
        // 返回结果
        return messages;
    }

    @Override
    public Message selectById(Long id) {
        //非空效验
        if(id==null || id<=0)
        {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Message message=messageMapper.selectByPrimaryKey(id);

        return message;
    }

    @Override
    public void updateStateById(Long id, Byte state) {

        //非空效验
        if(id==null || id<=0 ||state<0 || state>2)
        {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //更新对象
        Message updateMessage=new Message();
        updateMessage.setId(id);
        updateMessage.setState(state);
        Date date=new Date();
        updateMessage.setUpdateTime(date);

        // 调用DAO
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void reply(Long repliedId, Message message) {

        if(repliedId==null || repliedId<=0)
        {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //检验RepID站内信状态
        Message existsMessage=messageMapper.selectByPrimaryKey(repliedId);
        if(existsMessage==null ||existsMessage.getDeleteState()==1)
        {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
        //更新状态已恢复
        updateStateById(repliedId, (byte) 2);
        //写入数据库
        create(message);

    }
}
